package com.vf.admin.client.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppApplePaySelectDao;
import com.vf.admin.client.service.AppApplePaySelectService;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.AlipayConfigs;
import com.vf.admin.miaodong.entity.ApplePaySelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * <p>Title : </p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows10</p>
 *
 * @Author : NemoMeng
 * @Date 2023/6/28 15:23
 */
@Service
public class AppApplePaySelectServiceImpl implements AppApplePaySelectService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppApplePaySelectDao appApplePaySelectDao;


    @Override
    public ApplePaySelect getWeightPayInfo() {

        List<ApplePaySelect> applePaySelects = null;
        if (!redisUtil.hasKey(RedisKeys.APPLEPAYSELECT)) {
            applePaySelects = appApplePaySelectDao.list();
            redisUtil.set(RedisKeys.APPLEPAYSELECT, applePaySelects, RedisKeys.ALICONFIGSOUTTIME);
        } else {
            applePaySelects = (List<ApplePaySelect>) redisUtil.get(RedisKeys.APPLEPAYSELECT);
        }
        Integer sumWeight = 0;//总权重的值
        JSONArray as = new JSONArray();//存入对象用于概率
        Integer index = 0;
        for (int i = 0; i < applePaySelects.size(); i++) {
            Integer weight = applePaySelects.get(i).getWeight();
            if (weight > 0) {
                sumWeight = sumWeight + weight;
                for (int j = 0; j < weight; j++) {
                    as.add(index, applePaySelects.get(i));
                    index++;//放后面保证0也有值
                }
            }
        }
        Integer r = new Random().nextInt(sumWeight + 1);//随机数生成概率
        ApplePaySelect applePaySelect = (ApplePaySelect) as.get(r);
        System.out.println("权重：" + applePaySelect);
        return (ApplePaySelect) as.get(r);
    }
}
